package demo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class JiSuanQi extends JFrame implements ActionListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField tf;
	private JButton clear;
	private boolean isNew=true;
	private double result=0;
	private String preOperator="+";
	public JiSuanQi(){
		setSize(300, 400);
		setTitle("简易计算器");
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Font font=new Font("微软雅黑", Font.TRUETYPE_FONT, 24);
		JPanel p1=new JPanel();
		p1.setLayout(new BorderLayout());
		tf=new JTextField("0");
		tf.setHorizontalAlignment(JTextField.RIGHT);
		tf.setEnabled(false);
		tf.setDisabledTextColor(Color.BLUE);
		tf.setFont(font);
		clear=new JButton("清除");
		clear.addActionListener(this);
		clear.setFont(font);
		p1.add(tf);
		p1.add(clear,BorderLayout.EAST);
		add(p1,BorderLayout.NORTH);
		JPanel p2=new JPanel();
		p2.setLayout(new GridLayout(4, 4));
		String[] str={"7","8","9","+",
				"4","5","6","-",
				"1","2","3","*",
				"0",".","=","/"};
		for(String s:str){
			JButton bt=new JButton(s);
			bt.addActionListener(this);
			bt.setFont(font);                       
			bt.setBackground(new Color(0x0487C8));   
			bt.setForeground(new Color(0xffffff));               
			p2.add(bt);	
		}
		add(p2);
		
	}
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				new JiSuanQi();
			}
		});
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		String acmd=e.getActionCommand();
		if("0.123456789".indexOf(acmd)>=0)
			numInput(acmd);
		else if(acmd.equals("清除"))
			tf.setText("0");
		else calculator(acmd);
	}
    
	public void calculator(String op){
		isNew=true;
		double num=Double.valueOf(tf.getText());
		switch(preOperator){
		case "+":result+=num;break;
		case "-":result-=num;break;
		case "*":result*=num;break;
		case "/":result/=num;break;
		}
		String rst=String.valueOf(result);
		if(rst.endsWith(".0"))
			rst=rst.substring(0, rst.length()-2);
		tf.setText(rst);
		preOperator=op;
	}
	
	public void numInput(String num){
		String yuan=tf.getText();
		if(isNew) yuan="0";
		if(yuan.equals("0")){
			isNew=false;
			if(!num.equals("0")){
				if(num.equals(".")) tf.setText("0.");
				else tf.setText(num);
				return;
			}
		}
		else{
			if(yuan.indexOf(".")>=0&&num.equals(".")) return;
			tf.setText(yuan+num);
		}
	}
}